﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SockLib.Device.ModbusDevices
{
    /// <summary>
    /// <para>长沙泵：设备编号Did=3，功能码DOper如下：</para>
    /// <para>1:开泵，2：关泵</para>
    /// </summary>
    internal class CSPump : MBType
    {
        /// <summary>
        /// socket连接的IP地址
        /// </summary>
        public string IPAdress { get; set; }

        /// <summary>
        /// 长沙泵控制
        /// </summary>
        public CSPump() { }

        /// <summary>
        /// modbus数据分析
        /// </summary>
        /// <param name="buffer">收到的数据</param>
        /// <param name="res">解析后的字符串</param>
        /// <returns></returns>
        public bool DataAnaly(byte[] buffer,ref  ModbusData  res)
        { 
           if(! SockLib.Device.CRC  . CheckCrc(buffer,true  ))  //CRC校验是否正确,低位在前
                return false ;
            analy(buffer,ref  res);
            if (res.data.Count == 0)
                return false;
            return true;
        }

        /// <summary>
        /// 分析数据
        /// </summary>
        /// <param name="buffer">收到的字节数组</param>
        /// <param name="MBD">需要返回的modbusdata类</param>
        private void analy(byte[] buffer, ref ModbusData MBD)
        {
            MBD.device_id = buffer[0];
            MBD.device_cmd = buffer[1];
            MBD.IsLowBitFirst = true;
            MBD.recdata = buffer;
            MBD.Dtype = GetDeviceType();
            MBD.Did = GetDeviceId();
            MBD.data = new Dictionary<string, object>();
            if (buffer[2] * 256 + buffer[3] == 0x1000)
            {
                if (buffer[4] * 256 + buffer[5] == 1)
                {
                    MBD.data.Add("水泵开", 1);
                    MBD.DOper = 1;
                }
                else if (buffer[4] * 256 + buffer[5] == 5)
                {
                    MBD.data.Add("水泵关", 5);
                    MBD.DOper =2;
                }
            }
        }

        /// <summary>
        /// 获取modbus设备信息
        /// </summary>
        /// <returns></returns>
        public string GetDeviceType()
        {
            return "长沙泵";
        }

        /// <summary>
        /// 获得modbus设备类型ID
        /// </summary>
        /// <returns></returns>
        public int GetDeviceId()
        {
            return 2;
        }
    }
}
